package io.github.talelin.latticy.service.impl;

import io.github.talelin.latticy.dto.PointsRecordDTO;
import io.github.talelin.latticy.model.OrderDO;
import io.github.talelin.latticy.model.PointsRecordDO;
import io.github.talelin.latticy.service.OrderPointsService;
import io.github.talelin.latticy.service.PointsRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 订单积分处理服务实现类
 * @author talelin
 */
@Service
public class OrderPointsServiceImpl implements OrderPointsService {

    @Autowired
    private PointsRecordService pointsRecordService;

    @Override
    @Transactional
    public void processOrderPoints(OrderDO order) {
        if (order == null || order.getStatus() != 2) {
            // 订单状态不是已确认，不处理积分
            return;
        }

        BigDecimal payAmount = order.getPayAmount();
        if (payAmount == null || payAmount.compareTo(BigDecimal.ZERO) <= 0) {
            // 支付金额无效，不处理积分
            return;
        }

        // 处理卖家积分扣减（出售商品）
        if (order.getSaler() != null) {
            deductSellerPoints(order.getSaler(), payAmount, order.getId().longValue());
        }

        // 处理买家积分增加（购买商品）
        if (order.getUserId() != null) {
            addBuyerPoints(order.getUserId(), payAmount, order.getId().longValue());
        }
    }

    @Override
    @Transactional
    public void deductSellerPoints(Integer sellerId, BigDecimal amount, Long orderId) {
        if (sellerId == null || amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }

        // 创建积分扣减记录
        PointsRecordDTO pointsDto = new PointsRecordDTO();
        pointsDto.setUserId(sellerId.longValue());
        pointsDto.setPoints(-amount.intValue()); // 负数表示扣减
        pointsDto.setTitle("出售商品扣减积分");
        pointsDto.setDescription("出售商品获得" + amount + "元，扣减" + amount.intValue() + "积分");
        pointsDto.setSource("sale");
        pointsDto.setOrderId(orderId);

        try {
            PointsRecordDO record = pointsRecordService.deductPoints(pointsDto);
            System.out.println("卖家 " + sellerId + " 出售商品扣减积分: " + amount.intValue());
        } catch (Exception e) {
            System.err.println("卖家积分扣减失败: " + e.getMessage());
            throw e;
        }
    }

    @Override
    @Transactional
    public void addBuyerPoints(Integer buyerId, BigDecimal amount, Long orderId) {
        if (buyerId == null || amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }

        // 创建积分增加记录
        PointsRecordDTO pointsDto = new PointsRecordDTO();
        pointsDto.setUserId(buyerId.longValue());
        pointsDto.setPoints(amount.intValue()); // 正数表示增加
        pointsDto.setTitle("购买商品获得积分");
        pointsDto.setDescription("购买商品支付" + amount + "元，获得" + amount.intValue() + "积分");
        pointsDto.setSource("purchase");
        pointsDto.setOrderId(orderId);

        try {
            PointsRecordDO record = pointsRecordService.addPoints(pointsDto);
            System.out.println("买家 " + buyerId + " 购买商品获得积分: " + amount.intValue());
        } catch (Exception e) {
            System.err.println("买家积分增加失败: " + e.getMessage());
            throw e;
        }
    }

    @Override
    @Transactional
    public void rollbackOrderPoints(OrderDO order) {
        if (order == null) {
            return;
        }

        BigDecimal payAmount = order.getPayAmount();
        if (payAmount == null || payAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }

        try {
            // 回滚卖家积分（增加积分）
            if (order.getSaler() != null) {
                PointsRecordDTO sellerPointsDto = new PointsRecordDTO();
                sellerPointsDto.setUserId(order.getSaler().longValue());
                sellerPointsDto.setPoints(payAmount.intValue()); // 正数表示增加（回滚扣减）
                sellerPointsDto.setTitle("订单取消回滚积分");
                sellerPointsDto.setDescription("订单取消，回滚出售商品扣减的" + payAmount.intValue() + "积分");
                sellerPointsDto.setSource("order_cancel");
                sellerPointsDto.setOrderId(order.getId().longValue());
                
                pointsRecordService.addPoints(sellerPointsDto);
            }

            // 回滚买家积分（扣减积分）
            if (order.getUserId() != null) {
                PointsRecordDTO buyerPointsDto = new PointsRecordDTO();
                buyerPointsDto.setUserId(order.getUserId().longValue());
                buyerPointsDto.setPoints(-payAmount.intValue()); // 负数表示扣减（回滚增加）
                buyerPointsDto.setTitle("订单取消回滚积分");
                buyerPointsDto.setDescription("订单取消，回滚购买商品获得的" + payAmount.intValue() + "积分");
                buyerPointsDto.setSource("order_cancel");
                buyerPointsDto.setOrderId(order.getId().longValue());
                
                pointsRecordService.deductPoints(buyerPointsDto);
            }

            System.out.println("订单 " + order.getId() + " 积分回滚完成");
        } catch (Exception e) {
            System.err.println("订单积分回滚失败: " + e.getMessage());
            throw e;
        }
    }
}
